/**
 * By Alpha
 * Author: alixez <alixe.z@foxmail.com>
 * Date: 2017/11/16
 */

import modelExtend from 'dva-model-extend';
import { pageModel } from '../common';
import { routerTool, config } from 'utils';
import { queryMember, getEditInfo } from 'services/member';

export default modelExtend(pageModel, {
  namespace: 'member',

  state: {
    editModal: {
      modalType: 'create',
      visible: false,
      info: {},
    },
  },

  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === routerTool.getPathByName('OrganizationMember')) {
          const payload = location.query || { current: config.DefaultPager.page, pageSize: config.DefaultPager.pageSize };
          dispatch({
            type: 'loadMembers',
            payload,
          });
        }
      });
    },
  },

  effects: {
    *loadMembers ({ payload = {} }, { call, put }) {
      const { success, results } = yield call(queryMember, {
        page: payload.current,
        pageSize: payload.pageSize,
      });
      const { List, Total } = results;
      if (success && List) {
        yield put({
          type: 'loadSuccess',
          payload: {
            list: List,
            pagination: {
              current: Number(payload.current) || config.DefaultPager.page,
              pageSize: Number(payload.pageSize) || config.DefaultPager.pageSize,
              total: Total,
            },
          },
        });
      }
    },

    /**
     * 
     * @param {*} param0 
     * @param {*} param1 
     */
    *openEditModal ({ payload }, { call, put }) {
      const { id, modalType } = payload;
      if (id) {
        const { member } = yield call(getEditInfo, {
          id,
        });

        yield put({
          type: 'showEditModal',
          editModal: {
            modalType,
            visible: true,
            info: member,
          },
        });
      }
    },

  },

  reducers: {
    showEditModal (state, { editModal }) {

      const payload = {
        editModal: {
          ...editModal,
          visible: true,
        },
      };

      return {
        ...state,
        ...payload,
      };
    },

    hideEditModal (state) {
      // const payload = ;
      return {
        ...state,
        ...{
          editModal: {
            visible: false,
            info: {},
          },
        },
      };
    },


  },

});

